package com.julian.warehouse.activity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.julian.warehouse.R;
import com.julian.warehouse.adapter.LvAdapter;
import com.julian.warehouse.base.SPBaseActivity;
import com.julian.warehouse.bean.GoodsBean;
import com.julian.warehouse.database.GoodsTable;
import com.julian.warehouse.database.MyDBOpenHelper;
import com.julian.warehouse.utils.MyLog;

import java.util.ArrayList;
import java.util.List;

public class KucunActivity extends SPBaseActivity implements View.OnClickListener{

    private SQLiteDatabase db;
    private List<GoodsBean> list;
    private ListView lv;
    private PopupWindow popupWindow;
    private int currentPosition = 0;
    private EditText et_gname;
    private LvAdapter adapter;
    public static KucunActivity instance;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kucun);
        super.init();
        setHeadTitle(true,"商品库存",true);
        instance = this;
        mtvRight.setText("刷新");
        mtvRight.setOnClickListener(this);
    }

    @Override
    public void initView() {
         lv = (ListView) findViewById(R.id.lv);
        et_gname = (EditText) findViewById(R.id.et_gname);
        et_gname.addTextChangedListener(myWatcher);

    }

    @Override
    public void initData() {
        list = new ArrayList<>();
        adapter = new LvAdapter(this, list);
        lv.setAdapter(adapter);
        findAll();

    }

    private void findAll() {
        MyDBOpenHelper myDBOpenHelper = new MyDBOpenHelper(this);
        db = myDBOpenHelper.getReadableDatabase();
       /* Cursor cursor = db.query(
                 GoodsTable.TBL_NAME,
                 new String[]{
                         GoodsTable.COL_ID,
                         GoodsTable.COL_GNAME,
                         GoodsTable.COL_CTIME,
                         GoodsTable.COL_DESCRIPTION,
                         GoodsTable.COL_PICURL,
                         GoodsTable.COL_PRICE,
                         GoodsTable.COL_COUNT
                             },
                         GoodsTable.COL_GNAME+" =?",
                            new String[]{"哇哈哈"},
                            null,
                             null,
                            null,
                            null
             );*/

        //上面的查询方法比较烦，但不易出错
        String sql = "select * from "+GoodsTable.TBL_NAME;
        Cursor cursor = db.rawQuery(sql, null);
        list.clear();
        while(cursor.moveToNext()){
            GoodsBean goodsBean = new GoodsBean();
            goodsBean.setGname(cursor.getString(cursor.getColumnIndex(GoodsTable.COL_GNAME)));
            goodsBean.setCtime(cursor.getString(cursor.getColumnIndex(GoodsTable.COL_CTIME)));
            goodsBean.setDescription(cursor.getString(cursor.getColumnIndex( GoodsTable.COL_DESCRIPTION)));
            goodsBean.setPicurl(cursor.getString(cursor.getColumnIndex(GoodsTable.COL_PICURL)));
            goodsBean.setCount(cursor.getInt(cursor.getColumnIndex(GoodsTable.COL_COUNT)));
            goodsBean.setPrice(cursor.getDouble(cursor.getColumnIndex(GoodsTable.COL_PRICE)));
            goodsBean.setCost(cursor.getDouble(cursor.getColumnIndex(GoodsTable.COL_COST)));
            goodsBean.setId(cursor.getInt(cursor.getColumnIndex(GoodsTable.COL_ID)));
            list.add(goodsBean);
        }
        cursor.close();
        //db.close();

        adapter.notifyDataSetChanged();

        MyLog.i("AA","当前记录"+list.toString());

    }

    @Override
    public void initEvent() {

       lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              currentPosition = position;
              showPopWindow();

           }
       });
    }

    private void showPopWindow() {
        //让activity背景变灰色
        darkenBackground(0.5f);

        // 获取自定义布局文件activity_popupwindow_left.xml的视图
        View popupWindow_view = getLayoutInflater().inflate(R.layout.item_popwindow, null,false);
        // 创建PopupWindow实例,200,LayoutParams.MATCH_PARENT分别是宽度和高度
        popupWindow = new PopupWindow(popupWindow_view,LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT,true);
        // 设置动画效果
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);

        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_kucun, null);
        // 这里是位置显示方式,在屏幕的左侧
        popupWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);
        // 点击其他地方消失
        popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (popupWindow != null && popupWindow.isShowing()) {

                    popupWindow.dismiss();

                }
                return true;
            }
        });

        //结束的时候让activity背景还原
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                darkenBackground(1f);
            }
        });

        initPopItemView(popupWindow_view);


    }

    private void initPopItemView(View v) {
        GoodsBean gb = list.get(currentPosition);
        ((TextView)v.findViewById(R.id.tv_gname)).setText(gb.getGname());
        ((TextView)v.findViewById(R.id.tv_kucun)).setText("库存："+gb.getCount()+"");
        ((TextView)v.findViewById(R.id.tv_price)).setText("售价："+gb.getPrice()+"");
        ((TextView)v.findViewById(R.id.tv_cost)).setText(gb.getCost()+"");
        ((TextView)v.findViewById(R.id.tv_ctime)).setText(gb.getCtime());
        ((TextView)v.findViewById(R.id.tv_description)).setText(gb.getDescription());


        v.findViewById(R.id.btn_ruku).setOnClickListener(this);
        v.findViewById(R.id.btn_chuku).setOnClickListener(this);
    }


    /**
     * 改变背景颜色
     */
    private void darkenBackground(Float bgcolor){
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgcolor;

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);

    }



    private TextWatcher myWatcher =  new TextWatcher(){

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            findGoodsByName(s.toString().trim());
            MyLog.i("AA","触发afterTextChanged");

        }
    };




    private void findGoodsByName(String gname) {
        if (gname.equals("")){
            findAll();
            return;
        }

       /* MyDBOpenHelper myDBOpenHelper = new MyDBOpenHelper(this);
        db = myDBOpenHelper.getReadableDatabase();*/
        //上面的查询方法比较烦，但不易出错
        String sql = "select * from "+GoodsTable.TBL_NAME+" where GNAME LIKE '%"+gname+"%'";
        Cursor cursor = db.rawQuery(sql, null);
        list.clear();
        while(cursor.moveToNext()){
            GoodsBean goodsBean = new GoodsBean();
            goodsBean.setGname(cursor.getString(cursor.getColumnIndex(GoodsTable.COL_GNAME)));
            goodsBean.setCtime(cursor.getString(cursor.getColumnIndex(GoodsTable.COL_CTIME)));
            goodsBean.setDescription(cursor.getString(cursor.getColumnIndex( GoodsTable.COL_DESCRIPTION)));
            goodsBean.setPicurl(cursor.getString(cursor.getColumnIndex(GoodsTable.COL_PICURL)));
            goodsBean.setCount(cursor.getInt(cursor.getColumnIndex(GoodsTable.COL_COUNT)));
            goodsBean.setPrice(cursor.getDouble(cursor.getColumnIndex(GoodsTable.COL_PRICE)));
            goodsBean.setCost(cursor.getDouble(cursor.getColumnIndex(GoodsTable.COL_COST)));
            goodsBean.setId(cursor.getInt(cursor.getColumnIndex(GoodsTable.COL_ID)));

            list.add(goodsBean);
        }
        cursor.close();
        //db.close();

        adapter.notifyDataSetChanged();



    }







    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_ruku:
                GoodsBean goodsBean = list.get(currentPosition);
                Intent intent = new Intent(this, RukuActivity.class);
                intent.putExtra("ruku_item",goodsBean);
                startActivity(intent);

                break;
            case R.id.btn_chuku:
                GoodsBean goodsBean2 = list.get(currentPosition);
                Intent intent2 = new Intent(this, ChukuActivity.class);
                intent2.putExtra("chuku_item",goodsBean2);
                startActivity(intent2);
                break;
            case R.id.tv_share:
                findGoodsByName(et_gname.getText().toString().trim());
                break;
            default:break;
        }

    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        db.close();
    }
}
